<template>
	<view class="ConsultationPlusNewContainers">
		<view class="ConsultationPlusNewContainers_title">
			新增加做项目
		</view>
		
		<view class="ConsultationPlusNewContainers_top">
			<view class="ConsultationPlusNewContainers_top_tab">
				<view class="ConsultationPlusNewContainers_top_tab_item" :class="addactiveName=='first'?'active':''"
					@tap="changeTab({label:'first', isClear: false})">
					套餐
				</view>
				<view class="ConsultationPlusNewContainers_top_tab_item" :class="addactiveName=='second'?'active':''"
					@tap="changeTab({label:'second',isClear:false})">
					单项
				</view>
			</view>
			<view class="ConsultationPlusNewContainers_top_selectInfos">
				<view class="">
					共计：<text class="ConsultationPlusNewContainers_top_selectInfos_text">{{ihcTotal }}</text>元</text>
				</view>
				<view class="ConsultationPlusNewContainers_top_selectInfos_btn" @tap="showSelectLayStatus">
					已选加做项目
					<u-badge max="99" :value="ihcCheckedDataCopy.length"></u-badge>
				</view>


			</view>
		</view>
		<view class="ConsultationPlusNewContainers_input" v-if="addactiveName=='first'">
			<u--input clearable v-model="ihcPkgSearchKey" placeholder="输入套餐名" @input="handleInput(1)"></u--input>
		</view>
		<view class="ConsultationPlusNewContainers_input" v-if="addactiveName=='second'">
			<u--input clearable v-model="ihcPkgSearchKey" placeholder="输入单项名" @input="handleInput(1)"></u--input>
		</view>

		<scroll-view :style="{height:contentheightData}" :scroll-y="true" :refresher-enabled="false"
			:refresher-threshold="100" @scrolltolower='getReachBottom' @scroll="onScroll">

			<view class="ConsultationPlusNewContainers_content">
				<!-- 套餐 -->
				<block v-if="addactiveName=='first'">
					<view class="ConsultationPlusNewContainers_item" v-for="( item, index ) in  ihcAll " :key="index">
						<view class="ConsultationPlusNewContainers_item_left">
							<u-checkbox-group @change="getihcChecked(item, index)">
								<u-checkbox class="cardItem_box" size="28rpx" iconSize="24rpx"
									:checked='item.checked'></u-checkbox>
							</u-checkbox-group>
						</view>
						<view class="ConsultationPlusNewContainers_item_right">
							<view class="ConsultationPlusNewContainers_item_right_item">
								<view class="ConsultationPlusNewContainers_item_right_item_label">
									{{ item.name }}
								</view>
								<view class="ConsultationPlusNewContainers_item_right_item_infos">
									价格<text class="red">{{item.oriCost}}</text>元
								</view>
							</view>
						</view>

					</view>
				</block>
				<!-- 单项 -->
				<block v-else>
					<view class="ConsultationPlusNewContainers_item" v-for="( item, index ) in  ihcSubData "
						:key="index">
						<view class="ConsultationPlusNewContainers_item_left">
							<u-checkbox-group @change="getihcSubData(item, index)">
								<u-checkbox class="cardItem_box" size="28rpx" iconSize="24rpx"
									:checked='item.checked'></u-checkbox>
							</u-checkbox-group>
						</view>
						<view class="ConsultationPlusNewContainers_item_right">
							<view class="ConsultationPlusNewContainers_item_right_item">
								<view class="ConsultationPlusNewContainers_item_right_item_label">
									{{ item.name }}
								</view>
								<view class="ConsultationPlusNewContainers_item_right_item_infos">
									价格<text class="red">{{item.cost}}</text>元
								</view>
							</view>
						</view>

					</view>
				</block>
			</view>

			<u-loadmore :status="status" />
		</scroll-view>


		<view class="ConsultationPlusNewContainers_btnGroup">
			<u-button type="info" size="mini" text="取 消" style="width:100rpx;margin:0rpx 24rpx;"
				@tap="closed()"></u-button>
			<u-button type="primary" size="mini" text="确 定" style="width:100rpx;margin:0rpx 24rpx;"
				:disabled="(ihcCheckedDataCopy&&ihcCheckedDataCopy.length>0)?false:true" @tap="comfirm()"></u-button>
		</view>
		<!-- 弹窗  查看已选加做项目 -->
		<u-overlay :show="selectLayStatus" @click="''" zIndex='100'>
			<view class="selectLay_wrap" v-if="selectLayStatus">
				<view class="selectLay_wrap_content">
					<view class="ConsultationPlusNewContainers_title">
						已选加做项目
					</view>
					<view class="ConsultationPlusNewContainers_content active">
						<view class="ConsultationPlusNewContainers_item" v-for="( item, index ) in  ihcCheckedDataCopy "
							:key="index">
							<view class="ConsultationPlusNewContainers_item_left active">
								<view class="ConsultationPlusNewContainers_item_left_btn" @tap="decIncItem(item.id)">
									删除
								</view>
							</view>
							<view class="ConsultationPlusNewContainers_item_right">
								<view class="ConsultationPlusNewContainers_item_right_item">
									<view class="ConsultationPlusNewContainers_item_right_item_label">
										{{ item.name }}
									</view>
									<view class="ConsultationPlusNewContainers_item_right_item_infos">
										价格<text class="red">{{item.cost}}</text>元
									</view>
								</view>
							</view>


						</view>
					</view>
					<view class="ConsultationPlusNewContainers_btnGroup">
						<u-button type="info" size="mini" text="关 闭" style="width:100rpx;margin:0rpx 24rpx;"
							@tap="selectLayStatus=false"></u-button>

					</view>
				</view>
			</view>
		</u-overlay>
	</view>
</template>

<script>
	import _ from 'lodash'
	import moment from 'moment'
	import request from '@/utils/request'
	export default {
		name: "ConsultationPlusNew",
		props: ['orders', 'diagnosisId'],
		data() {
			return {
				status: 'loadmore',
				contentheightData: 'calc(80vh - 250rpx)',
				selectLayStatus: false, //已选叫做项目套餐
				disease: '', //专病
				addactiveName: '',
				ihcSubData: [], //单项列表
				ihcPkgSearchKey: '', //筛选关键词
				ihcChecked: [], //选中的套餐id
				ihcAll: [], //套餐列表
				ihcCheckedDataCopy: [], //选中的单项
				ihcCheckedDataCopyIdS: [], //选中的单项 id
				pageInfo: { // 分页信息
					size: 15,
					page: 1,
					total: 0
				},
				tab: {},
			}
		},
		watch: {
			ihcChecked(newVal, oldVal) {
				let delArray = _.difference(oldVal, newVal)
				this.decPake(delArray)
			},
		},
		computed: {
			ihcTotal() {
				let price = 0
				if (this.ihcCheckedDataCopy.length > 0) {
					this.ihcCheckedDataCopy.forEach(temp => {
						price += Number(temp.cost)
					})
				}
				return price.toFixed(2)
			},

		},
		mounted() {
			this.changeTab({
				label: 'first',
				isClear: false
			})

		},
		methods: {

			showSelectLayStatus() {
				console.log("999")
				console.log(this.ihcCheckedDataCopy.length)
				if (this.ihcCheckedDataCopy.length > 0) {
					console.log("///***")
					this.selectLayStatus = true
				}

			},
			//获取选中的单项id
			getihcCheckedDataCopyIdS() {
				this.ihcCheckedDataCopyIdS = []
				let data = this.ihcCheckedDataCopy
				data.forEach(item => {
					this.ihcCheckedDataCopyIdS.push(item.id)
				})
			},

			//删除套餐
			decPake(val) {
				console.log("执行***************decpak   start")
				let ihcCheckedDataCopyIdSString = val.join(',')
				// console.log(this.ihcCheckedDataCopy.length)
				let len = this.ihcCheckedDataCopy.length
				let oldarray = []
				let oldarrayId = []
				if (val.length > 0) {
					for (let i = 0; i < len; i++) {
						// console.log('I' + i)
						if (ihcCheckedDataCopyIdSString.indexOf(this.ihcCheckedDataCopy[i].packageId) > -1) {
							oldarray.push(this.ihcCheckedDataCopy[i])
							oldarrayId.push(this.ihcCheckedDataCopy[i].id)
						}
					}
					this.ihcCheckedDataCopy = _.difference(this.ihcCheckedDataCopy, oldarray)
					this.ihcCheckedDataCopyIdS = _.difference(this.ihcCheckedDataCopyIdS, oldarrayId)
					console.log("执行***************decpak   end")
				}
			},
			getihcSubData(item, index) { //选中单项
				console.log("///66*单项")
				if (item.checked) {
					item.checked = false
				} else {
					item.checked = true
				}
				this.$set(this.ihcSubData, index, item)

				this.getihcSubDatadArr(item) //
			},
			getihcSubDatadArr(item) { //选中单项
				// this.ihcCheckedDataCopy = []
				// const ihcCheckedDataCopy = []
				// this.ihcSubData.forEach((t, index) => {
				// 	if (t.checked) {
				// 		ihcCheckedDataCopy.push(t)
				// 	}
				// })
				// console.log(ihcCheckedDataCopy)
				// this.ihcCheckedDataCopy = ihcCheckedDataCopy
				// this.ihcSubCheckedChange(item)
				
				if(item.checked){
					this.ihcCheckedDataCopy.push(item)
				}else{
					this.ihcCheckedDataCopy=this.ihcCheckedDataCopy.filter(temp=>{
						return temp.id!==item.id
					})
				}
				
				this.ihcSubCheckedChange()
			},
			getihcChecked(item, index) { //选择套餐
				if (item.checked) {
					item.checked = false
				} else {
					item.checked = true
				}
				this.$set(this.ihcAll, index, item)

				this.getihcCheckedArr(item) //
			},
			getihcCheckedArr(item) { //选中套餐
				// this.ihcChecked = []
				// const ihcChecked = []
				// this.ihcAll.forEach((t, index) => {
				// 	if (t.checked) {
				// 		ihcChecked.push(t.id)
				// 	}

				// })
				// console.log(ihcChecked)
				// this.ihcChecked = ihcChecked
				// this.handleCheckedIhcChange(ihcChecked)
				
				if(item.checked){
					this.ihcChecked.push(item.id)
				}else{
					this.ihcChecked=this.ihcChecked.filter(temp=>{
						return temp!==item.id
					})
				}
				console.log('this.ihcChecked--',this.ihcChecked)
				this.handleCheckedIhcChange(this.ihcChecked)
			},
			ihcSubCheckedChange() { //添加单项
				this.getihcCheckedDataCopyIdS()
			},
			handleCheckedIhcChange(val) { //套餐
				console.log("套餐")
				console.log(val)
				let ihcCheckedDataCopyIdSString = this.ihcCheckedDataCopyIdS.join(',') //将选中的单项id转成字符串
				if (val.length > 0) {
					val.forEach(id => {
						this.ihcAll.forEach(eid => {
							if (eid.id === id) {
								eid.doctorAdviceList.forEach(temp => {
									if (ihcCheckedDataCopyIdSString.indexOf(temp.id) == -1) {
										temp.packageId = eid.id
										this.ihcCheckedDataCopy.push(temp)

									}

								})
							}
						})
					})
				}
				this.getihcCheckedDataCopyIdS()
				console.log("this.ihcChecked" + this.ihcChecked)
				// this.decPake(val, ihcCheckedDataCopyIdSString)
			},
			decIncItem(val) {
				if (this.ihcCheckedDataCopy.length === 1) {
					this.ihcCheckedDataCopy = []
					this.ihcCheckedDataCopyIdS = []
					this.ihcChecked = []
				} else {
					for (let i = 0; i < this.ihcCheckedDataCopy.length; i++) {
						if (this.ihcCheckedDataCopy[i].id === val) {
							// console.log("this.ihcCheckedDataCopy[i].packageId" + this.ihcCheckedDataCopy[i].packageId)
							if (this.ihcCheckedDataCopy[i].packageId) {
								this.changeihcCheckedIds(this.ihcCheckedDataCopy[i].packageId)
							}
							this.ihcCheckedDataCopy.splice(i, 1)

						}
					}
					// console.log("删除//////" + val)
					this.changeihcCheckedDataCopyIdS(val)
				}


			},
			changeihcCheckedIds(val) {
				for (let i = 0; i < this.ihcChecked.length; i++) {
					console.log(i)
					if (this.ihcChecked[i] === val) {
						this.ihcChecked.splice(i, 1)
					}
				}
			},
			changeihcCheckedDataCopyIdS(val) {
				console.log(this.ihcCheckedDataCopyIdS)
				for (let i = 0; i < this.ihcCheckedDataCopyIdS.length; i++) {
					console.log(i)
					if (this.ihcCheckedDataCopyIdS[i] === val) {
						this.ihcCheckedDataCopyIdS.splice(i, 1)
					}
				}
			},
			onScroll(e) {
				// 传入scrollTop值并触发所有easy-loadimage组件下的滚动监听事件
				this.scrollTop = e.detail.scrollTop;
				// console.log(e)
			},
			getReachBottom() {
				console.log("888")
				let that = this;
				this.status = 'loading';
				this.pageInfo.page = ++this.pageInfo.page;
				setTimeout(() => {
					let params = {
						name: that.ihcPkgSearchKey,
						institutionId: that.orders.serviceCenterId,
						applicableTumors: that.disease,
						page: that.pageInfo.page - 1,
						size: that.pageInfo.size,
					}
					if(that.tab.label == 'first'){//套餐
						if (that.ihcAll.length < that.pageInfo.total) {
							that.status = 'loadmore'
							that.changeTabAgain(that.tab, params)
						} else {
							that.status = 'nomore'
						}
					}else{ //单项
						if (that.ihcSubData.length < that.pageInfo.total) {
							that.status = 'loadmore'
							that.changeTabAgain(that.tab, params)
						} else {
							that.status = 'nomore'
						}
					}
					

				}, 600)
			},
			handleInput(num){
				if(num==1){
					this.ihcPkgSearchKey = uni.$u.trim(this.ihcPkgSearchKey)
					this.ihcAll = []
					this.ihcSubData = []
					this.pageInfo.page = 1
					let params = {
						name: this.ihcPkgSearchKey,
						institutionId: this.orders.serviceCenterId,
						applicableTumors: this.disease,
						page: this.pageInfo.page - 1,
						size: this.pageInfo.size,
					}
					this.changeTabAgain(this.tab, params)
					
				}
			},
			changeTab(tab) {

				if (this.addactiveName == tab.label) {
					return false
				}
				this.ihcAll = []
				this.ihcSubData = []
				this.addactiveName = tab.label
				this.tab = tab

				if (!this.tab.isClear) {
					this.ihcPkgSearchKey = ''
					this.disease = ''
				}
				this.pageInfo.page = 1
				let params = {
					name: this.ihcPkgSearchKey,
					institutionId: this.orders.serviceCenterId,
					applicableTumors: this.disease,
					page: this.pageInfo.page - 1,
					size: this.pageInfo.size,
				}
				this.changeTabAgain(this.tab, params)


			},
			changeTabAgain(tab, params) { //切换导航

				if (tab.label == 'first') { //套餐
					try {
						request({
							method: 'get',
							url: '/doctor-advice-packages/all/list/page',
							params: params
						}).then(
							res => {
								if (res.code === 200) {
									// 设置数据列表
									let data = res.data
									//getPackagePrice
									data.forEach(item => {
										if (this.ihcChecked.includes(item.id)) {
											item.checked = true
										} else {
											item.checked = false
										}


										item.cost = item.discount //this.getPackagePrice(item.doctorAdviceList)
										item.oriCost = this.getPackagePrice(item.doctorAdviceList)
									})

									// this.ihcAll = data
									this.ihcAll.push(...data)
									//设置页码
									this.pageInfo = {
										total: res.pageInfo.total,
										page: res.pageInfo.page + 1,
										size: res.pageInfo.size
									}
									if (this.ihcAll.length < res.pageInfo.total) {
										this.status = 'loadmore'
									} else {
										this.status = 'nomore'
									}

								}
							},
							err => {
								this.$u.toast(err.response.data)
							}
						)
					} catch (e) {
						console.log('请求失败')
					}
				} else { //单项
					// 请求查询接口
					try {
						request({
							method: 'get',
							url: `/doctor-advices/findAllDoctorAdvice/handler/page`, //doctor-advices/findAllDoctorAdvice/handler
							params: params
						}).then(
							res => {
								if (res.code === 200) {
									// 设置数据列表
									let data = res.data
									//getPackagePrice
									data.forEach(item => {
										if (this.ihcCheckedDataCopyIdS.includes(item.id)) {
											item.checked = true
										} else {
											item.checked = false
										}

									})
									// this.ihcSubData = data
									this.ihcSubData.push(...data)
									//设置页码
									this.pageInfo = {
										total: res.pageInfo.total,
										page: res.pageInfo.page + 1,
										size: res.pageInfo.size
									}
									if (this.ihcSubData.length < res.pageInfo.total) {
										this.status = 'loadmore'
									} else {
										this.status = 'nomore'
									}

								}
							},
							err => {
								this.$u.toast(err.response.data)
							}
						)
					} catch (e) {
						console.log('请求失败')
					}
				}
			},
			getPackagePrice(list) {
				let allPrice = 0
				list.forEach(item => {
					allPrice += item.cost
				})
				return parseFloat(allPrice.toFixed(2))
			},
			closed() {
				this.$emit('closed')
			},
			comfirm() {
				let finallyData = []
				const words = []
				finallyData = this.ihcCheckedDataCopy
				this.ihcCheckedDataCopy.forEach(temp => {
					words.push(temp.id)
				})
				if (finallyData.length > 0) {
					try {
						request({
							method: 'post',
							url: `/diagnosis/extra-project?doctorAdviceIds=${words.join()}&patientsId=${this.orders.patients[0].id}&diagnosisId=${this.diagnosisId}`
						}).then(
							res => {
								if (res.code === 200) {
									this.$u.toast('添加成功')
									this.$emit('plusAddComfirm')
								}
							},
							err => {
								this.$u.toast(`${err.response.data}`)
							}
						)
					} catch (e) {
						console.log('请求失败')
					}
				} else {
					this.$u.toast('请选择加做项目')
				}

			}

		}
	}
</script>

<style lang="scss" scoped>
	.selectLay {
		&_wrap {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 100%;

			&_content {
				width: 90%;
				height: 80vh;
				border-radius: 12rpx;
				background: #fff;
			}
		}
	}

	.ConsultationPlusNewContainers {
		width: 100%;
		height: 100%;

		&_title {
			text-align: center;
			font-size: 30rpx;
			font-weight: 700;
			line-height: 50rpx;
		}
		&_input{
			padding: 10rpx 20rpx;
		}

		&_top {
			padding: 0 16rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			&_tab {
				display: flex;
				align-items: center;

				&_item {
					width: 100rpx;
					height: 44rpx;
					font-size: 26rpx;
					text-align: center;
					border: 2rpx solid #fff;
					line-height: 44rpx;
				}

				&_item.active {
					color: #fff;
					background: rgb(55, 112, 246);
					border: 2rpx solid rgb(55, 112, 246);
				}
			}

			&_selectInfos {
				font-size: 24rpx;
				display: flex;
				align-items: center;

				&_text {
					color: red;
					font-size: 26rpx;
					margin: 0 2rpx;
				}

				&_btn {
					margin-left: 6rpx;
					position: relative;
					color: #fff;
					background: rgb(55, 112, 246);
					height: 44rpx;
					font-size: 24rpx;
					padding: 0 16rpx;
					text-align: center;
					line-height: 44rpx;

					/deep/ .u-badge {
						top: -12rpx !important;
						right: -10rpx !important;
					}
				}
			}
		}

		&_content.active {
			height: calc(100% - 110rpx);
		}

		&_content {
			// height: calc(100% - 200rpx);
			padding: 0 24rpx;
			// overflow-y: auto;
		}

		&_btnGroup {
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		&_item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			// border-bottom: 2rpx solid #ddd;
			padding: 8rpx 0;

			&_left.active {
				width: 80rpx;
			}

			&_left {
				width: 40rpx;

				&_btn {
					color: rgb(55, 112, 246);
					font-size: 26rpx;
				}
			}

			&_right {
				width: calc(100% - 40rpx);
				display: flex;
				align-items: center;
				font-size: 26rpx;
				line-height: 40rpx;

				&_item:last-child {
					margin-right: 0rpx;
				}

				&_item {
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-right: 12rpx;

					&_label {
						color: #333;

					}

					&_infos {
						color: #333;
					}
				}
			}
		}
	}
</style>